<template>
  <KView class="sys-textarea">
    <template v-if="disabled">
      <textarea v-if="isMiniprogram" class="sys-textarea-input" v-model="text" :maxlength="-1" :disable-default-padding="true" :disabled="true"
        :auto-height="true"></textarea>
    </template>
    <template v-else>
      <KView class="sys-textarea-placeholder" v-if="placeholder!==''&&text===''">
        {{placeholder}}
      </KView>
      <KView>
        <textarea class="sys-textarea-input" :class="{'show-limit':showWordLimit}" v-model="text" :maxlength="maxlength"
          :disable-default-padding="true" @change="handleChange" @input="handleInput"></textarea>
        <KView v-if="showWordLimit" class="sys-textarea-count">{{len}}/{{maxlength}}</KView>
      </KView>
    </template>
  </KView>
</template>

<script>
  export default {
    props: {
      value: {
        type: String,
        required: true
      },
      placeholder: {
        type: String,
        default: ''
      },
      maxlength: {
        type: Number,
        default: -1
      },
      showWordLimit: {
        type: Boolean,
        default: false
      },
      nowarp: {
        type: Boolean,
        default: false
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },

    watch: {
      value() {
        if (this.inputText !== null) {
          this.inputText = null;
          return;
        }
        this.text = this.value;
      }
    },

    data() {
      return {
        isMiniprogram: process.env.isMiniprogram,
        text: this.value,
        inputText: null,
        len: this.value.length
      };
    },

    methods: {
      handleInput() {
        if (this.nowarp) {
          let text = this.text;
          this.text = text.replace(/\n/g, '');
        }

        let text = this.text;
        if (text === this.value) {
          return;
        }

        this.inputText = text;
        this.$emit('input', text);
        this.len = this.text.length;
      },

      handleChange() {
        let text = this.text;
        this.$emit('change', text);
      }
    }
  };

</script>

<style lang="scss">
  .sys-textarea {
    height: 100%;
    position: relative;
    line-height: 1.4;

    >div {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }

    .sys-textarea-placeholder {
      color: #aeaeae;
      z-index: 1;
    }

    .sys-textarea-input {
      width: 100%;
      height: 100%;
      z-index: 2;
      border: none;
      background: none;
      resize: none;
      padding: 0;
      color: inherit;
      line-height: inherit;
      font-size: inherit;

      &.show-limit {
        height: calc(100% - #{formatPx(36)});
      }
    }

    .sys-textarea-count {
      color: #aeaeae;
      font-size: formatPx(24);
      text-align: right;
      height: formatPx(26);
      line-height: formatPx(26);
      margin-top: formatPx(10);
    }
  }

</style>
